from django.shortcuts import render, reverse, redirect
from django.db import connection


def get_cursor():
    cursor = connection.cursor()
    return cursor


def index(request):
    cursor = get_cursor()
    cursor.execute('select * from book')
    result = cursor.fetchall()
    context = {
        "result": result
    }
    return render(request, "index.html", context=context)


def add_book(request):
    if request.method == "GET":
        return render(request, "add.html")
    else:
        name = request.POST.get('name')
        author = request.POST.get('author')
        cursor = get_cursor()
        cursor.execute("insert into book(id, book, author) values (null, '%s', '%s' )" % (name, author))
        return redirect(reverse('index'))


def book_detail(request, book_id):
    cursor = get_cursor()
    if request.method == "GET":
        cursor.execute("SELECT * FROM book WHERE id = '%s'" % book_id)
        result = cursor.fetchall()
        context = {
            "result": result
        }
        return render(request, "detail.html", context=context)
    else:
        cursor.execute("DELETE FROM book WHERE id = '%s'" % book_id)
        return redirect(reverse('index'))
